/**
 * 利用express-ws创建wss服务；注意这个只能在主进程（如 src/main/index.ts）中加载
 *  只是个演示，生产中其实不需要也不建议在本地搭建WSS服务
 */
import expressWs from "express-ws";
/**
 * 引入http服务器
 */
import {createServer, Server} from "http";
import app from "./wsRouters";

/**
 * 初始化WS服务，并设置最大传输文件大小
 */
const port = 8888;
class WsServer {
	server: Server;

	constructor(app: any) {
		app.set("port", port);
		this.server = createServer(app);
		expressWs(app, this.server, {
			wsOptions: {maxPayload: 5 * 1024 * 1024 * 1024},
		});
	}

	startServer() {
		return new Promise((resolve: (value: string) => void, reject) => {
			try {
				this.server.listen(port);
				resolve("内置WS服务端已经启动");
			} catch (error) {
				switch (error.code) {
					case "ERR_SERVER_ALREADY_LISTEN":
						resolve("WS服务端已经启动");
						break;
					case "EACCES":
						reject("权限不足WS服务器启动失败，请使用管理员权限运行。");
						break;
					case "EADDRINUSE":
						reject("WS服务器端口已被占用，请检查。");
						break;
					default:
						reject(error);
				}
			}
		});
	}

	stopServer() {
		return new Promise((resolve: (value: string) => void, reject) => {
			this.server.close((err) => {
				if (err) {
					switch ((err as any).code) {
						case "ERR_SERVER_NOT_RUNNING":
							resolve("WS服务端未启动");
							break;
						default:
							reject(err);
					}
				} else {
					resolve("WS服务端已关闭");
				}
			});
		});
	}
}

const myServer = new WsServer(app);
export default {
	StartServer() {
		return myServer.startServer();
	},
	StopServer() {
		return myServer.stopServer();
	},
};
